var user = getCookie("userName");

$(function () {
  console.log(user);
  $("#questionNameDetail").html("欢迎使用题库系统");
  var oTable = new TableInit();
  oTable.Init();
});

// XXX问卷答题情况明细
function freshTable() {
  $("#countTable").bootstrapTable('refresh');
}

function TableInit() {

  var oTableInit = {};
  //初始化Table
  oTableInit.Init = function () {
    $('#countTable').bootstrapTable({
      url: httpRequestUrl + '/getQuestionByTitle',         //请求后台的URL（*）
      method: 'POST',                      //请求方式（*）
      striped: true,                      //是否显示行间隔色
      pagination: true,                   //是否显示分页（*）
      //是否启用排序
      sortOrder: "asc",                   //排序方式
      sortStable: true,                   //是否排序
      queryParamsType: '',//默认值为 'limit',传给服务端的参数为：limit, offset, search, sort, order Else
      dataType: 'json',
      paginationShowPageGo: true,
      showJumpto: true,
      pageNumber: 1, //初始化加载第一页，默认第一页
      queryParams: queryParams,//请求服务器时所传的参数
      sidePagination: 'server',//指定服务器端分页
      pageSize: 10,//单页记录数
      pageList: [10, 20, 30, 40],//分页步进值
      search: false, //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
      silent: true,
      showRefresh: false,                  //是否显示刷新按钮
      showToggle: false,
      minimumCountColumns: 2,             //最少允许的列数
      uniqueId: "id",                     //每一行的唯一标识，一般为主键列

      columns: [{
        checkbox: true,
        visible: false
      }, {
        field: 'id',
        title: '序号',
        align: 'center',
        formatter: function (value, row, index) {
          return index + 1;
        }
      },
        {
          field: 'questionType',
          title: '题目类型',
          align: 'center',
          /*sortable : true*/
        },
        {
          field: 'questionTitle',
          title: '题目标题',
          align: 'center',
          /*sortable : true*/
        },
        {
          field: 'questionOption',
          title: '题目选项',
          align: 'center',
          width: '200px',
          /*sortable : true*/
        },
        {
          field: 'important',
          title: '是否必答',
          align: 'center',
          width: '90px',
          /*sortable : true*/
        },
        {
          field: 'operation',
          title: '选择',
          width: '90px',
          align: 'center',
          events: operateEvents,//给按钮注册事件
          formatter: addFunctionAlty//表格中增加按钮
        }],
      responseHandler: function (res) {
        //console.log(res);
        if (res.code === "666") {
          var answerInfo = res.data.list;
          console.log(answerInfo);
          var NewData = [];
          if (answerInfo.length) {
            for (var i = 0; i < answerInfo.length; i++) {

              var dataNewObj = {
                'id': '',
                "questionType": '',
                'questionTitle': '',
                "questionOption": '',
                'important': '',
                "uid": "",
              };
              dataNewObj.id = '' + i;
              dataNewObj.uid = answerInfo[i].id;
              var questionType = answerInfo[i].questionType;
              if (questionType === "0") {
                dataNewObj.questionType = '单选题';
              } else if (questionType === "1") {
                dataNewObj.questionType = '多选题';
              } else if (questionType === "2") {
                dataNewObj.questionType = '填空题';
              } else if (questionType === "3") {
                dataNewObj.questionType = '矩阵量表';
              } else if (questionType === "4") {
                dataNewObj.questionType = '量表题';
              } else {
                dataNewObj.questionType = '其他';
              }
              dataNewObj.questionTitle = answerInfo[i].questionTitle;
              var questionOption = answerInfo[i].questionOption;
              //将json字符串转换为数组
              var questionOptionArr = JSON.parse(questionOption);
              //如果questionOptionArr为空
              if (questionOptionArr.length === 0) {
                dataNewObj.questionOption = "无选项";
              } else {
                //遍历数组
                var questionOptionStr = '';
                for (var j = 0; j < questionOptionArr.length; j++) {
                  questionOptionStr += questionOptionArr[j].optionWord + "；";
                }
                //去掉最后一个分号
                questionOptionStr = questionOptionStr.substring(0,
                    questionOptionStr.length - 1);
                dataNewObj.questionOption = questionOptionStr;
              }
              dataNewObj.important = answerInfo[i].important;
              NewData.push(dataNewObj);
            }
            var data = {
              total: res.data.total,
              rows: NewData
            };
          } else {
            var data = {
              rows: NewData
            };
          }
          return data;
        } else {
          var data = {
            rows: []
          };
          return data;
        }

      }
    });
  };

  // 得到查询的参数
  function queryParams(params) {
    var questionTitle = $("#keyWord").val();
    var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
      pageNum: params.pageNumber,
      pageSize: params.pageSize,
      questionTitle: questionTitle,
    };
    return JSON.stringify(temp);
  }

  return oTableInit;
}

window.operateEvents = {
  //编辑
  'click #btn_count': function (e, value, row, index) {
    id = row.id;
    $.cookie('questionId', id);
  }
};

// 表格中按钮
function addFunctionAlty(value, row, index) {
  var btnText = '';
  //加入选择框
  btnText += '<input type="checkbox" name="check" value="' + row.uid + '">';
  return btnText;
}

function getReport() {

  //下载报告
  $("#countTable").tableExport({
    type: "excel",
    escape: "false",
    fileName: getCookie("nameOfQuestionnaire") + '答题情况明细'
  });

}

//设计问卷
function designQuestionnaire() {
  var ifDesignQuestionnaire = getCookie("ifDesignQuestionnaire");
  if (ifDesignQuestionnaire == "false") {
    layer.msg("问卷处于运行状态或问卷已发布，不可设计问卷", {icon: 2})
  } else {
    $.cookie("QuestionId", getCookie("questionId"));
    window.open('designQuestionnaire.html')
  }
}

//发送问卷
function ifSendQuestionnaire() {
  var ifSendQuestionnaire = getCookie("ifSendQuestionnaire");
  if (ifSendQuestionnaire === "false") {
    layer.msg("问卷处于未发送或暂停的状态，不可发送问卷", {icon: 2})
  } else {
    $.cookie("QuestionId", getCookie("questionId"));
    window.location.href = 'sendQuestionnaire.html';
  }
}

//回车事件
$(document).keydown(function (event) {
  if (event.keyCode === 13) {
    freshTable();
  }
});

//返回主页
function backhome() {
  window.location.href = 'myQuestionnaires.html'
}

//批量导入
function batchImport() {
  //获取选择框的值
  var check = $("input[name='check']:checked");
  var checkValue = [];
  for (var i = 0; i < check.length; i++) {
    checkValue.push(check[i].value);
  }
  console.log(checkValue);
  if (checkValue.length === 0) {
    layer.msg("请选择要导入的题目")
  } else {
    data = {
      "idList": JSON.stringify(checkValue),
      "questionId": getCookie("questionId")
    }
    commonAjaxPost(true, "/addQuestionnaireQuestion", data, function (res) {
      console.log(res.data);
      if (res.code === "666") {
        //弹出提示确认框
        layer.confirm('导入成功!', {
          btn: ['确定'] //按钮
        }, function () {
          var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
          parent.layer.close(index); //再执行关闭
          //刷新父页面
          parent.location.reload();
        });
      } else {
        layer.msg("导入失败，请重新尝试", {icon: 2});
      }
    })
  }
}

//批量创建
function batchCreate() {
  deleteCookie("isCreateQuestion");
  $.cookie("isCreateQuestion", "true");
  deleteCookie("isImportQuestion");
  $.cookie("isImportQuestion", "true");
  window.location.href = 'designQuestion.html';
}
